﻿using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System;

namespace MCMLXVII.Core.Common.BackEnd
{
    [Serializable()]
    public class XMLSerializableHashTable : IXmlSerializable
    {
        private Hashtable _HT;

        public XMLSerializableHashTable()
        {
            _HT = new Hashtable();
        }
        public XMLSerializableHashTable(Hashtable ht)
        {
            _HT = ht;
        }

        public void Add(string key, object value)
        {
            _HT.Add(key, value);
        }

        public bool ContainsKey(string key)
        {
            return _HT.ContainsKey(key);
        }
        
        public void Clear()
        {
            _HT.Clear();
        }

        public object this[object key]
        {
            get { return _HT[key]; }
            set { _HT[key] = value; }
        }

        public IDictionary GetItems()
        {
            return (IDictionary)_HT;
        }

        public ICollection GetKeys()
        {
            return _HT.Keys ;
        }

        
        System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            reader.Read();
            //reader.ReadStartElement("item");
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                string key = reader.GetAttribute("key");
                string type = reader.GetAttribute("type");

                reader.ReadStartElement("item");
                
                Type t = System.Type.GetType(type);
                XmlSerializer xs = new XmlSerializer(t);
                object value = xs.Deserialize(reader);
                reader.ReadEndElement();
                reader.MoveToContent();
                //
                _HT.Add(key, value);
            }
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            foreach (object key in _HT.Keys)
            {
                object value = _HT[key];
                writer.WriteStartElement("item");
                writer.WriteAttributeString("key", key.ToString());
                writer.WriteAttributeString("type", value.GetType().ToString());  
                XmlSerializer xs = new XmlSerializer(value.GetType());
                xs.Serialize(writer, value);
                writer.WriteEndElement();
            }
        }
    }

}

